<template>
  <div class="PictureWithAi">
    <div class="picture-with-ai">
      <div v-for="message in messages" :key="message.id" :class="message.type">
        <div v-if="message.type=='bot'">
          <img :src="message.avatar" alt="avatar" class="avatar">
          <div class="message-info">
            <strong>{{ message.name }}: </strong>
            <img v-if="message.imgInfo.uniqueID!=''" :src="message.imgInfo.uniqueID" class="message-img" />
            <template v-if="message.imgInfo.text!=''">
              {{ message.imgInfo.text }}
            </template>
          </div>
        </div>
        <div v-else>
          <div>
            <template v-if="message.imgInfo.text!=''">
              {{ message.imgInfo.text }}
            </template>
            <img v-if="message.imgInfo.uniqueID!=''" :id="message.imgInfo.uniqueID" class="message-img" />
            <strong>: {{ message.name }}</strong>
            <img :src="message.avatar" alt="avatar" class="avatar">
          </div>
        </div>
      </div>
      <div class="select-container">
        <Select v-model="picCount" @on-change="handleChange" style="width: 120px">
          <Option v-for="n in 4" :value="n" :key="n">{{ n }}</Option>
        </Select>
      </div>
    </div>
    <br>
    <Row type="flex" align="middle" justify="center">
      <Col span="20">
        <Input v-model="userInput" type="textarea" size="large" @on-enter="sendMessageForKeyBoard" placeholder="请在这输入你的图片描述..." :autosize="{minRows: 2}" >
          <template #append>
            <Button icon="ios-search"></Button>
          </template>
        </Input>
      </Col>
      <Col span="1">

      </Col>
      <Col span="3">
        <Button type="primary" @click="picVisible=true" icon="ios-camera">发送图片素材生成</Button>
      </Col>
    </Row>
    <AiPictureHandle @modalClose="modalCloseDeal" @sendFormData="getSendFormData" v-if="picVisible"/>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator'
import {picWithAiUrl} from "@/common/HttpRequestUrl"
import AiPictureHandle from "@/components/AiPictureHandle.vue"

@Component({
  components: {
    AiPictureHandle
  }
})
export default class PictureWithAi extends Vue {

  //  图片上传按钮
  picVisible = false
  picCount = 1

  //  机器人头像
  botHeadPortrait = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F61cd5aa2-9d83-4b5c-88b0-7aa83f44a365%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1685277914&t=ad05553a40099d851400f76077e057ac'
  //  用户头像
  userHeadPortrait = 'https://img0.baidu.com/it/u=1833087554,1820670932&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
  messages = [
    {
      id: 1,
      name: 'Bot',
      imgInfo: {
        uniqueID:'',
        text:'你好，我是来自openai的智能图形模型，很高兴为你服务'
      },
      avatar: this.botHeadPortrait,
      type:"bot"
    }
  ]

  userId = Math.random().toString()
  userInput = ''

  sendMessageForKeyBoard(){
    this.sendMessage(null);
  }
  sendMessage(data) {

    let formData = new FormData();
    if ( data == null ) {
      this.sendTextToChatFrame(this.userInput);
      // 将 Blob 对象添加到 FormData 对象
      formData.append('prompt', this.userInput);
    }else {
      this.sendPicToChatFrame(data);
      formData = data.sendFormData;
    }

    formData.append('picCount', this.picCount.toString());
    let thisObj = this
    this.$post(picWithAiUrl,formData).then(function (res) {
      if ( res.status ) {
        res.data.forEach((url) => {
          thisObj.messages.push({ id: thisObj.messages.length + 1, name: 'Bot', imgInfo:{uniqueID:url,text:''},avatar:thisObj.botHeadPortrait,type:'bot' })
        });
        thisObj.picScrollDown();
      }else {
        thisObj.$Message.error("ai响应错误，请重试！")
      }
    }).finally(function () {
      //  对话框下拉条自动往下滚
      thisObj.picScrollDown();
    })
    this.userInput = ''
  }

  modalCloseDeal(data){
    this.picVisible = false
  }
  getSendFormData(res){
    let thisObj = this
    thisObj.picVisible = false
    res.then(function (data) {
      if ( data == null ) {
        thisObj.$Message.error('请补充图片相关数据');
        thisObj.picVisible = false
        return;
      }
      thisObj.sendMessage(data);
    })
  }

  sendPicToChatFrame( data ){
    const timestamp = new Date().getTime();
    const randomNumber = Math.floor(Math.random() * 100000000);
    const uniqueID = timestamp + '_' + randomNumber;
    this.messages.push({ id: this.messages.length + 1, name: 'You', imgInfo:{uniqueID:uniqueID,text:data.prompt},avatar:this.userHeadPortrait,type:'user' })

    this.$nextTick(() => {  // 确保图片元素已经被渲染到页面上之后再执行
      const element = document.getElementById(uniqueID);
      const imgEl = element instanceof HTMLImageElement ? element : null;
      if (imgEl) {
        imgEl.src = data.croppedImageDataUrl;
        //  对话框下拉条自动往下滚
        this.picScrollDown();

        this.$Message.success("图片发送成功！")
      }
    });
  }
  sendTextToChatFrame(text){
    let thisObj = this
    thisObj.messages.push({ id: this.messages.length + 1, name: 'You', imgInfo:{uniqueID:'',text:text},avatar:this.userHeadPortrait,type:'user' })
    //  对话框下拉条自动往下滚
    thisObj.picScrollDown();
  }
  handleChange(value) {
    this.picCount = value;
  }
  picScrollDown(){
    //  对话框下拉条自动往下滚
    this.$nextTick(() => {
      let chatBox = this.$el.querySelector('.picture-with-ai')
      chatBox.scrollTop = chatBox.scrollHeight
    })
  }
}
</script>

<style scoped lang="less">
.PictureWithAi {
  background: url('https://5b0988e595225.cdn.sohucs.com/images/20171101/e09988856ce04941a7ab5d305525e269.gif') no-repeat center center fixed;
  background-size: cover;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 60px;
}

.picture-with-ai {
  border: 1px solid #d3d3d3;
  border-radius: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  height: 70vh;
  margin: 0 auto;
  overflow-y: scroll;
  padding: 10px;
  width: 80%;
  background-color: white;
}

.picture-with-ai strong {
  margin-top: 5px;
  font-size: 18px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  font-weight: 600;
  line-height: 1.4;
  letter-spacing: 0.5px;
  color: #4d4d4d;
  text-shadow: 1px 1px #ffffff;
}

.picture-with-ai div {
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
  align-items: center;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.bot {
  text-align: left;
  color: #ffc800;
}

.user {
  ext-align: right;
  color: #35bbdc;
  justify-content: flex-end;
  align-self: flex-end;
}
.message-img {
  width: 100%;
  max-width: 450px;
  height: auto;
  display: block;
  margin-bottom: 10px;
  box-sizing: border-box;
  border-radius: 5px;
}
.select-container {
  position: absolute;
  bottom: 10px;
  left: 10px;
}
</style>
